import { archService } from "@/mdesign-lib/mdesign-app.umd.js";
import { Action } from "@/mdesign-lib/mdesign-app.umd.js";
import { FHJSImportWindow, CloseData } from "../customWindows/FHJSImport";
import { FHJSExportWindow, CloseData as ExportCloseData } from "../customWindows/FHJSExport";
import { MenuItem } from "@/mdesign-lib/mdesign-app.umd.js";
import { getUid } from "@/util/common";
import { ActionKey } from "@/mdesign-lib/mdesign-app.umd.js";
import { archUtil } from "@/mdesign-lib/mdesign-app.umd.js";

export class FHJSImportAction extends Action {
  keyName = "FHJSImport" as ActionKey;
  desc = "FHJSImport";

  async run(type: 1 | 2) {
    const projectId = app.activeProject!.id;
    const solutionCode = archUtil.getCasic3SolutionCode();
    const uuid = getUid();
    const windowConfig = {};
    if (solutionCode) {
      Object.assign(windowConfig, { height: 350 });
    } else {
      Object.assign(windowConfig, { height: 250 });
    }
    await FHJSImportWindow.popup({ projectId, type, uuid, windowConfig }, async res => {
      const { success, ownerId, filePath, filePaths } = res as Required<CloseData>;
      if (success) {
        await archService.importForFHJS(projectId, ownerId, uuid, solutionCode, filePath, filePaths).catch(() => {
          FHJSImportWindow.abort();
        });
      }
    }).then(res => {
      if (res.success) {
        app.$notify({ type: "success", title: "成功", message: "导入成功" });
      }
    });
  }

  onSysMenuClick(menu: MenuItem) {
    this.run(menu.type);
  }
}

export class FHJSExportAction extends Action {
  keyName = "FHJSExport" as ActionKey;
  desc = "FHJSExport";

  async run() {
    const projectId = app.activeProject!.id;
    await FHJSExportWindow.popup({ projectId }, async res => {
      const { success, ownerId } = res as Required<ExportCloseData>;
      if (success) {
        const solutionCode = archUtil.getCasic3SolutionCode();
        const token = archUtil.getCasic3Token();
        const isSuccess = await archService.exportForFHJS(projectId, ownerId, solutionCode, token);
        if (isSuccess) {
          app.$notify({ type: "success", title: "成功", message: "导出成功" });
        } else {
          app.$notify({ type: "error", title: "失败", message: "导出失败" });
        }
        FHJSExportWindow.abort();
        FHJSExportWindow.done();
      }
    });
  }

  onSysMenuClick() {
    this.run();
  }
}
